package com.ruoyi.system.api.service.impl;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.ruoyi.common.config.JPushConfig;
import com.ruoyi.common.config.PushConfig;
import com.ruoyi.common.jpush.JPushClientUtil;
import com.ruoyi.common.utils.AMapUtils;
import com.ruoyi.common.utils.LngLat;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.mapper.*;
import com.ruoyi.system.api.service.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName TaskServiceImpl
 * @Description: TODO
 * @Author shihx
 * @Date 2020-04-02
 * @Version V1.0
 **/
@Service
public class TaskServiceImpl implements TaskService {
    private static final Logger log = LoggerFactory.getLogger(TaskServiceImpl.class);

    @Autowired
    private PlanDetailsMapper planDetailsMapper;

    @Autowired
    private JPushConfig jPushConfig;

    @Autowired
    private JpushLogMapper jpushLogMapper;

    @Autowired
    private ServiceDetailsMapper serviceDetailsMapper;

    @Autowired
    private FseLocationMapper fseLocationMapper;

    @Autowired
    private FseLocationLogMapper fseLocationLogMapper;


    @Override
    public void waitingForTheDoor(TaskPush taskPush, String serveAdvanceTipsTime) {
        List<TaskPush> taskPushes = planDetailsMapper.getWaitingForTheDoor(taskPush);
        if (taskPushes != null && taskPushes.size() > 0) {
            for (TaskPush push : taskPushes) {
                if (StringUtils.isNotEmpty(push.getRegistrationId())) {
                    Date date = new Date();
                    String content = PushConfig.DOOR_CONTENT
                            .replaceAll("客户名称", push.getCustomerName())
                            .replaceAll("N", serveAdvanceTipsTime);
                    // 推送额外参数
                    JsonObject extra = new JsonObject();
                    extra.addProperty("type", PushConfig.DOOR_STATE);
//                    extra.addProperty("serviceNoticeId", push.getServiceNoticeId());
//                    extra.addProperty("serviceNo", push.getServiceNo());
//                    extra.addProperty("planId", push.getId());
                    extra.addProperty("enginnerId", push.getFseId());
                    extra.addProperty("enginnerName", push.getFseName());

                    JpushLog jpushLog = new JpushLog();
                    PushResult pushResult = null;
                    try {

                        JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                        pushResult = JPushClientUtil.getInstance().sendPush(push.getRegistrationId(), PushConfig.DOOR_TITLE, content, extra);

                        jpushLog.setStatuscode(pushResult.statusCode + "");
                        jpushLog.setMsgId(pushResult.msg_id + "");
                        jpushLog.setSendno(pushResult.sendno + "");
                    } catch (APIConnectionException e) {
                        // Connection error, should retry later
                        log.error("Connection error, should retry later", e);
                    } catch (APIRequestException e) {
                        // Should review the error, and fix the request
                        log.error("Should review the error, and fix the request", e);
                        log.info("HTTP Status: " + e.getStatus());
                        log.info("Error Code: " + e.getErrorCode());
                        log.info("Error Message: " + e.getErrorMessage());
                        jpushLog.setStatuscode(e.getErrorCode() + "");
                        jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                    }
                    // 保存推送日志
                    jpushLog.setEnginnerId(push.getFseId());
                    jpushLog.setType(PushConfig.ONE_PUSH);
                    jpushLog.setRegistrationId(push.getRegistrationId());
                    jpushLog.setState(PushConfig.DOOR_STATE);
//                    jpushLog.setNoticeId(push.getServiceNoticeId());
//                    jpushLog.setServiceNo(push.getServiceNo());
                    jpushLog.setTitle(PushConfig.DOOR_TITLE);
                    jpushLog.setContent(content);
                    jpushLog.setExtra(extra.toString());
                    jpushLog.setPushTime(date);
                    jpushLog.setCreateTime(date);
                    jpushLogMapper.insertJpushLog(jpushLog);

                    // 如果状态为0 说明推送成功
                    if ("0".equals(jpushLog.getStatuscode())) {
                        TaskPush taskPush1 = new TaskPush();
                        taskPush1.setState("1");
                        taskPush1.setCustomerName(push.getCustomerName());
                        taskPush1.setDoorInPush("1");
                        taskPush1.setDoorInPushTime(new Date());
                        taskPush1.setEstimatedVisitingTime(push.getEstimatedVisitingTime());
                        taskPush1.setFseId(push.getFseId());
                        planDetailsMapper.updateTaskPlanDetail(taskPush1);
                    }

                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signIn1(TaskPush taskPush) {
        try {
            List<TaskPush> taskPushes = planDetailsMapper.getSignIn1(taskPush);
            if (taskPushes != null && taskPushes.size() > 0) {
                for (TaskPush push : taskPushes) {
                    if (StringUtils.isNotEmpty(push.getRegistrationId())) {
                        Date date = new Date();
                        String content = PushConfig.SIGN_IN_CONTENT1.replaceAll("客户名称", push.getCustomerName());
                        // 推送额外参数
                        JsonObject extra = new JsonObject();
                        extra.addProperty("type", PushConfig.SIGN_IN_STATE);
                        extra.addProperty("enginnerId", push.getFseId());
                        extra.addProperty("enginnerName", push.getFseName());

                        JpushLog jpushLog = new JpushLog();
                        PushResult pushResult = null;
                        try {
                            JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                            pushResult = JPushClientUtil.getInstance().sendPush(push.getRegistrationId(), PushConfig.SIGN_IN_TITLE, content, extra);

                            jpushLog.setStatuscode(pushResult.statusCode + "");
                            jpushLog.setMsgId(pushResult.msg_id + "");
                            jpushLog.setSendno(pushResult.sendno + "");
                        } catch (APIConnectionException e) {
                            // Connection error, should retry later
                            log.error("Connection error, should retry later", e);
                        } catch (APIRequestException e) {
                            // Should review the error, and fix the request
                            log.error("Should review the error, and fix the request", e);
                            log.info("HTTP Status: " + e.getStatus());
                            log.info("Error Code: " + e.getErrorCode());
                            log.info("Error Message: " + e.getErrorMessage());
                            jpushLog.setStatuscode(e.getErrorCode() + "");
                            jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                        }
                        // 保存推送日志
                        jpushLog.setEnginnerId(push.getFseId());
                        jpushLog.setType(PushConfig.ONE_PUSH);
                        jpushLog.setRegistrationId(push.getRegistrationId());
                        jpushLog.setState(PushConfig.SIGN_IN_STATE);
                        jpushLog.setTitle(PushConfig.SIGN_IN_TITLE);
                        jpushLog.setContent(content);
                        jpushLog.setExtra(extra.toString());
                        jpushLog.setPushTime(date);
                        jpushLog.setCreateTime(date);
                        jpushLogMapper.insertJpushLog(jpushLog);

                        // 如果状态为0 说明推送成功
                        if ("0".equals(jpushLog.getStatuscode())) {
                            TaskPush taskPush1 = new TaskPush();
                            taskPush1.setState("1");
                            taskPush1.setCustomerName(push.getCustomerName());
                            taskPush1.setSignInPush("1");
                            taskPush1.setSignInPushTime(date);
                            taskPush1.setEstimatedVisitingTime(push.getEstimatedVisitingTime());
                            taskPush1.setFseId(push.getFseId());
                            planDetailsMapper.updateTaskPlanDetail(taskPush1);
                        }

                    }
                }
            }
        } catch (Exception e) {
            log.error("程序异常", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signIn2(TaskPush taskPush) {
        try {
            List<TaskPush> taskPushes = planDetailsMapper.getSignIn2(taskPush);
            if (taskPushes != null && taskPushes.size() > 0) {
                HashMap<String, TaskPush> hashMap = new HashMap<String, TaskPush>();
                // 通过MAP过滤重复数据
                for (TaskPush push : taskPushes) {
                    hashMap.put(push.getWeiyi(), push);
                }
                // 遍历处理数据
                for (Map.Entry<String, TaskPush> entry : hashMap.entrySet()) {
                    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
                    TaskPush push = entry.getValue();
                    if (StringUtils.isNotEmpty(push.getRegistrationId()) && push.getPostX() != null && push.getPostY() != null && push.getLongitude() != null && push.getLatitude() != null) {
                        // 人员的实时经纬度
                        LngLat start = new LngLat(push.getPostX(), push.getPostY());

                        // 获取仪器的经纬度
                        LngLat end = new LngLat(push.getLongitude(), push.getLatitude());

                        // 计算获取两组经纬度的距离 取公里KM
                        double actualDistance = AMapUtils.calculateLineDistance(start, end) / 1000;
                        // 如果在这个范围内 推送消息
                        if (actualDistance <= Double.parseDouble(taskPush.getDistance())) {

                            Date date = new Date();
                            String content = PushConfig.SIGN_IN_CONTENT2.replaceAll("客户名称", push.getCustomerName());
                            // 推送额外参数
                            JsonObject extra = new JsonObject();
                            extra.addProperty("type", PushConfig.SIGN_IN_STATE);
                            extra.addProperty("enginnerId", push.getFseId());
                            extra.addProperty("enginnerName", push.getFseName());

                            JpushLog jpushLog = new JpushLog();
                            PushResult pushResult = null;
                            try {
                                JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                                pushResult = JPushClientUtil.getInstance().sendPush(push.getRegistrationId(), PushConfig.SIGN_IN_TITLE, content, extra);

                                jpushLog.setStatuscode(pushResult.statusCode + "");
                                jpushLog.setMsgId(pushResult.msg_id + "");
                                jpushLog.setSendno(pushResult.sendno + "");
                            } catch (APIConnectionException e) {
                                // Connection error, should retry later
                                log.error("Connection error, should retry later", e);
                            } catch (APIRequestException e) {
                                // Should review the error, and fix the request
                                log.error("Should review the error, and fix the request", e);
                                log.info("HTTP Status: " + e.getStatus());
                                log.info("Error Code: " + e.getErrorCode());
                                log.info("Error Message: " + e.getErrorMessage());
                                jpushLog.setStatuscode(e.getErrorCode() + "");
                                jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                            }
                            // 保存推送日志
                            jpushLog.setEnginnerId(push.getFseId());
                            jpushLog.setType(PushConfig.ONE_PUSH);
                            jpushLog.setRegistrationId(push.getRegistrationId());
                            jpushLog.setState(PushConfig.SIGN_IN_STATE);
                            jpushLog.setTitle(PushConfig.SIGN_IN_TITLE);
                            jpushLog.setContent(content);
                            jpushLog.setExtra(extra.toString());
                            jpushLog.setPushTime(date);
                            jpushLog.setCreateTime(date);
                            jpushLogMapper.insertJpushLog(jpushLog);

                            // 如果状态为0 说明推送成功
                            if ("0".equals(jpushLog.getStatuscode())) {
                                TaskPush taskPush1 = new TaskPush();
                                taskPush1.setState("1");
                                taskPush1.setCustomerName(push.getCustomerName());
                                taskPush1.setSignInPush1("1");
                                taskPush1.setSignInPushTime1(date);
                                taskPush1.setEstimatedVisitingTime(push.getEstimatedVisitingTime());
                                taskPush1.setFseId(push.getFseId());
                                planDetailsMapper.updateTaskPlanDetail(taskPush1);
                            }
                        }

                    }
                }

            }
        } catch (Exception e) {
            log.error("程序异常", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signOff1(TaskPush taskPush) {
        try {
            List<TaskPush> taskPushes = planDetailsMapper.getSignOff1(taskPush);
            if (taskPushes != null && taskPushes.size() > 0) {
                for (TaskPush push : taskPushes) {
                    if (StringUtils.isNotEmpty(push.getRegistrationId())) {
                        Date date = new Date();
                        String content = PushConfig.SIGN_OFF_CONTENT1.replaceAll("客户名称", push.getCustomerName());
                        // 推送额外参数
                        JsonObject extra = new JsonObject();
                        extra.addProperty("type", PushConfig.SIGN_OFF_STATE);
                        extra.addProperty("enginnerId", push.getFseId());
                        extra.addProperty("enginnerName", push.getFseName());

                        JpushLog jpushLog = new JpushLog();
                        PushResult pushResult = null;
                        try {
                            JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                            pushResult = JPushClientUtil.getInstance().sendPush(push.getRegistrationId(), PushConfig.SIGN_OFF_TITLE, content, extra);

                            jpushLog.setStatuscode(pushResult.statusCode + "");
                            jpushLog.setMsgId(pushResult.msg_id + "");
                            jpushLog.setSendno(pushResult.sendno + "");
                        } catch (APIConnectionException e) {
                            // Connection error, should retry later
                            log.error("Connection error, should retry later", e);
                        } catch (APIRequestException e) {
                            // Should review the error, and fix the request
                            log.error("Should review the error, and fix the request", e);
                            log.info("HTTP Status: " + e.getStatus());
                            log.info("Error Code: " + e.getErrorCode());
                            log.info("Error Message: " + e.getErrorMessage());
                            jpushLog.setStatuscode(e.getErrorCode() + "");
                            jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                        }
                        // 保存推送日志
                        jpushLog.setEnginnerId(push.getFseId());
                        jpushLog.setType(PushConfig.ONE_PUSH);
                        jpushLog.setRegistrationId(push.getRegistrationId());
                        jpushLog.setState(PushConfig.SIGN_OFF_STATE);
                        jpushLog.setTitle(PushConfig.SIGN_OFF_TITLE);
                        jpushLog.setContent(content);
                        jpushLog.setExtra(extra.toString());
                        jpushLog.setPushTime(date);
                        jpushLog.setCreateTime(date);
                        jpushLogMapper.insertJpushLog(jpushLog);

                        // 如果状态为0 说明推送成功
                        if ("0".equals(jpushLog.getStatuscode())) {
                            TaskPush taskPush1 = new TaskPush();
                            taskPush1.setState("2");
                            taskPush1.setCustomerName(push.getCustomerName());
                            taskPush1.setSignOffPush("1");
                            taskPush1.setSignOffPushTime(date);
                            taskPush1.setSignInTime(push.getSignInTime());
                            taskPush1.setFseId(push.getFseId());
                            planDetailsMapper.updateTaskPlanDetail(taskPush1);
                        }

                    }
                }
            }
        } catch (Exception e) {
            log.error("程序异常", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signOff3(TaskPush taskPush) {
        try {
            List<TaskPush> taskPushes = planDetailsMapper.getSignOff3(taskPush);
            if (taskPushes != null && taskPushes.size() > 0) {
                for (TaskPush push : taskPushes) {
                    if (StringUtils.isNotEmpty(push.getRegistrationId())) {
                        Date date = new Date();
                        String content = PushConfig.SIGN_OFF_CONTENT1.replaceAll("客户名称", push.getCustomerName());
                        // 推送额外参数
                        JsonObject extra = new JsonObject();
                        extra.addProperty("type", PushConfig.SIGN_OFF_STATE);
                        extra.addProperty("enginnerId", push.getFseId());
                        extra.addProperty("enginnerName", push.getFseName());

                        JpushLog jpushLog = new JpushLog();
                        PushResult pushResult = null;
                        try {
                            JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                            pushResult = JPushClientUtil.getInstance().sendPush(push.getRegistrationId(), PushConfig.SIGN_OFF_TITLE, content, extra);

                            jpushLog.setStatuscode(pushResult.statusCode + "");
                            jpushLog.setMsgId(pushResult.msg_id + "");
                            jpushLog.setSendno(pushResult.sendno + "");
                        } catch (APIConnectionException e) {
                            // Connection error, should retry later
                            log.error("Connection error, should retry later", e);
                        } catch (APIRequestException e) {
                            // Should review the error, and fix the request
                            log.error("Should review the error, and fix the request", e);
                            log.info("HTTP Status: " + e.getStatus());
                            log.info("Error Code: " + e.getErrorCode());
                            log.info("Error Message: " + e.getErrorMessage());
                            jpushLog.setStatuscode(e.getErrorCode() + "");
                            jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                        }
                        // 保存推送日志
                        jpushLog.setEnginnerId(push.getFseId());
                        jpushLog.setType(PushConfig.ONE_PUSH);
                        jpushLog.setRegistrationId(push.getRegistrationId());
                        jpushLog.setState(PushConfig.SIGN_OFF_STATE);
                        jpushLog.setTitle(PushConfig.SIGN_OFF_TITLE);
                        jpushLog.setContent(content);
                        jpushLog.setExtra(extra.toString());
                        jpushLog.setPushTime(date);
                        jpushLog.setCreateTime(date);
                        jpushLogMapper.insertJpushLog(jpushLog);

                        // 如果状态为0 说明推送成功
                        if ("0".equals(jpushLog.getStatuscode())) {
                            TaskPush taskPush1 = new TaskPush();
                            taskPush1.setState("2");
                            taskPush1.setCustomerName(push.getCustomerName());
                            taskPush1.setSignOffPush("1");
                            taskPush1.setSignOffPushTime(date);
                            taskPush1.setSignInTime(push.getSignInTime());
                            taskPush1.setFseId(push.getFseId());
                            planDetailsMapper.updateTaskPlanDetail(taskPush1);
                        }

                    }
                }
            }
        } catch (Exception e) {
            log.error("程序异常", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signOff2(TaskPush taskPush, String serveEndTipsTime) {
        try {
            List<TaskPush> taskPushes = planDetailsMapper.getSignOff2(taskPush);
            if (taskPushes != null && taskPushes.size() > 0) {
                HashMap<String, TaskPush> hashMap = new HashMap<String, TaskPush>();
                // 通过MAP过滤重复数据
                for (TaskPush push : taskPushes) {
                    hashMap.put(push.getWeiyi(), push);
                }
                // 遍历处理数据
                for (Map.Entry<String, TaskPush> entry : hashMap.entrySet()) {
//                    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
                    TaskPush push = entry.getValue();
                    if (StringUtils.isNotEmpty(push.getRegistrationId()) && push.getPostX() != null && push.getPostY() != null && push.getLongitude() != null && push.getLatitude() != null) {
                        // 人员的实时经纬度
                        LngLat start = new LngLat(push.getPostX(), push.getPostY());

                        // 获取仪器的经纬度
                        LngLat end = new LngLat(push.getLongitude(), push.getLatitude());

                        // 计算获取两组经纬度的距离 取公里KM
                        double actualDistance = AMapUtils.calculateLineDistance(start, end) / 1000;
                        // 如果在这个范围外 推送消息
                        if (actualDistance >= Double.parseDouble(taskPush.getDistance())) {

                            Date date = new Date();
                            String content = PushConfig.SIGN_OFF_CONTENT2.replaceAll("客户名称", push.getCustomerName())
                                    .replaceAll("N", serveEndTipsTime);
                            // 推送额外参数
                            JsonObject extra = new JsonObject();
                            extra.addProperty("type", PushConfig.SIGN_OFF_STATE);
                            extra.addProperty("enginnerId", push.getFseId());
                            extra.addProperty("enginnerName", push.getFseName());

                            JpushLog jpushLog = new JpushLog();
                            PushResult pushResult = null;
                            try {
                                JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                                pushResult = JPushClientUtil.getInstance().sendPush(push.getRegistrationId(), PushConfig.SIGN_OFF_TITLE, content, extra);

                                jpushLog.setStatuscode(pushResult.statusCode + "");
                                jpushLog.setMsgId(pushResult.msg_id + "");
                                jpushLog.setSendno(pushResult.sendno + "");
                            } catch (APIConnectionException e) {
                                // Connection error, should retry later
                                log.error("Connection error, should retry later", e);
                            } catch (APIRequestException e) {
                                // Should review the error, and fix the request
                                log.error("Should review the error, and fix the request", e);
                                log.info("HTTP Status: " + e.getStatus());
                                log.info("Error Code: " + e.getErrorCode());
                                log.info("Error Message: " + e.getErrorMessage());
                                jpushLog.setStatuscode(e.getErrorCode() + "");
                                jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                            }
                            // 保存推送日志
                            jpushLog.setEnginnerId(push.getFseId());
                            jpushLog.setType(PushConfig.ONE_PUSH);
                            jpushLog.setRegistrationId(push.getRegistrationId());
                            jpushLog.setState(PushConfig.SIGN_OFF_STATE);
                            jpushLog.setTitle(PushConfig.SIGN_OFF_TITLE);
                            jpushLog.setContent(content);
                            jpushLog.setExtra(extra.toString());
                            jpushLog.setPushTime(date);
                            jpushLog.setCreateTime(date);
                            jpushLogMapper.insertJpushLog(jpushLog);

                            // 如果状态为0 说明推送成功
                            if ("0".equals(jpushLog.getStatuscode())) {
                                TaskPush taskPush1 = new TaskPush();
                                taskPush1.setState("2");
                                taskPush1.setCustomerName(push.getCustomerName());
                                taskPush1.setSignOffPush1("1");
                                taskPush1.setSignOffPushTime1(date);
                                taskPush1.setSignInTime(push.getSignInTime());
                                taskPush1.setFseId(push.getFseId());
                                planDetailsMapper.updateTaskPlanDetail(taskPush1);
                            }
                        }

                    }
                }

            }
        } catch (Exception e) {
            log.error("程序异常", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signOffStartTime(TaskPush taskPush, String serve_end_tips_time) {
        try {
            List<TaskPush> taskPushes = planDetailsMapper.getSignOffStartTime(taskPush);
            if (taskPushes != null && taskPushes.size() > 0) {
                HashMap<String, TaskPush> hashMap = new HashMap<String, TaskPush>();
                // 通过MAP过滤重复数据
                for (TaskPush push : taskPushes) {
                    hashMap.put(push.getWeiyi(), push);
                }
                // 遍历处理数据
                for (Map.Entry<String, TaskPush> entry : hashMap.entrySet()) {
                    TaskPush push = entry.getValue();
                    if (push.getPostX() != null && push.getPostY() != null && push.getLongitude() != null && push.getLatitude() != null) {
                        // 人员的实时经纬度
                        LngLat start = new LngLat(push.getPostX(), push.getPostY());

                        // 获取仪器的经纬度
                        LngLat end = new LngLat(push.getLongitude(), push.getLatitude());

                        // 计算获取两组经纬度的距离 取公里KM
                        double actualDistance = AMapUtils.calculateLineDistance(start, end) / 1000;
                        // 如果在这个范围外 推送消息
                        if (actualDistance >= Double.parseDouble(taskPush.getDistance())) {
                            Date now = new Date();
                            int aftertime = Integer.parseInt(serve_end_tips_time) * 60 * 1000;
                            Date afterDate = new Date(now.getTime() + aftertime);
                            PlanDetails planDetails = new PlanDetails();
                            planDetails.setId(push.getId());
                            PlanDetails planDetailsSetTime = planDetailsMapper.getPlanDetails(planDetails);
                            planDetailsSetTime.setSignOffPushTime1(afterDate);
                            planDetailsSetTime.setSignOffPushFlag("1");
                            planDetailsMapper.updateStPlanDetails(planDetailsSetTime);
                        }

                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("程序异常", e.getMessage());
            // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void fillInLog(TaskPush taskPush) {
        try {
            List<TaskPush> taskPushes = planDetailsMapper.getFillInLog(taskPush);
            if (taskPushes != null && taskPushes.size() > 0) {
                for (TaskPush push : taskPushes) {
                    if (StringUtils.isNotEmpty(push.getRegistrationId())) {
                        Date date = new Date();
                        String content = PushConfig.FILL_IN_LOG_CONTENT.replaceAll("C", push.getServiceNo());
                        // 推送额外参数
                        JsonObject extra = new JsonObject();
                        extra.addProperty("type", PushConfig.FILL_IN_LOG_STATE);
                        extra.addProperty("serviceNoticeId", push.getServiceNoticeId());
                        extra.addProperty("serviceNo", push.getServiceNo());
                        extra.addProperty("planId", push.getId());
                        extra.addProperty("enginnerId", push.getFseId());
                        extra.addProperty("enginnerName", push.getFseName());

                        JpushLog jpushLog = new JpushLog();
                        PushResult pushResult = null;
                        try {
                            JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                            pushResult = JPushClientUtil.getInstance().sendPush(push.getRegistrationId(), PushConfig.FILL_IN_LOG_TITLE, content, extra);

                            jpushLog.setStatuscode(pushResult.statusCode + "");
                            jpushLog.setMsgId(pushResult.msg_id + "");
                            jpushLog.setSendno(pushResult.sendno + "");
                        } catch (APIConnectionException e) {
                            // Connection error, should retry later
                            log.error("Connection error, should retry later", e);
                        } catch (APIRequestException e) {
                            // Should review the error, and fix the request
                            log.error("Should review the error, and fix the request", e);
                            log.info("HTTP Status: " + e.getStatus());
                            log.info("Error Code: " + e.getErrorCode());
                            log.info("Error Message: " + e.getErrorMessage());
                            jpushLog.setStatuscode(e.getErrorCode() + "");
                            jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                        }
                        // 保存推送日志
                        jpushLog.setEnginnerId(push.getFseId());
                        jpushLog.setType(PushConfig.ONE_PUSH);
                        jpushLog.setNoticeId(push.getServiceNoticeId());
                        jpushLog.setServiceNo(push.getServiceNo());
                        jpushLog.setRegistrationId(push.getRegistrationId());
                        jpushLog.setState(PushConfig.FILL_IN_LOG_STATE);
                        jpushLog.setTitle(PushConfig.FILL_IN_LOG_TITLE);
                        jpushLog.setContent(content);
                        jpushLog.setExtra(extra.toString());
                        jpushLog.setPushTime(date);
                        jpushLog.setCreateTime(date);
                        jpushLogMapper.insertJpushLog(jpushLog);

                        // 如果状态为0 说明推送成功
                        if ("0".equals(jpushLog.getStatuscode())) {
                            PlanDetails planDetails = new PlanDetails();
                            planDetails.setId(push.getId());
                            planDetails.setFillInLogPush("1");
                            planDetails.setFillInLogPushNum(1L);
                            planDetails.setFillInLogPushTime(date);
                            planDetailsMapper.updateStPlanDetails(planDetails);
                        }

                    }
                }
            }
        } catch (Exception e) {
            log.error("程序异常", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }


    public Date addHour(Date date, double hour) {
        long time = date.getTime(); // 得到指定日期的毫秒数
        hour = hour * 60 * 60 * 1000; // 要加上hour的小时数转换成毫秒数
        time += hour; // 相加得到新的毫秒数
        return new Date(time); // 将毫秒数转换成日期
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void signOffAutoPush(TaskPush taskPush) {
        try {
            List<TaskPush> taskPushes = planDetailsMapper.getSignOffAutoPush(taskPush);
            if (taskPushes != null && taskPushes.size() > 0) {
                Date date = new Date();
                Date departMent = null;
                for (TaskPush push : taskPushes) {
                    departMent = addHour(push.getEstimatedDepartureTime(), push.getSignOffAutoHour());
                    // 判断是否是已经删除的数据，如果是已经删除的数据不推送，直接更新推送标识和时间
                    if (!"0".equals(push.getDelFlag())) {
                        PlanDetails planDetails = new PlanDetails();
                        planDetails.setId(push.getId());
                        planDetails.setSignOffAutoPush("1");
                        planDetails.setSignOffAutoPushTime(departMent);
                        planDetailsMapper.updateStPlanDetails(planDetails);
                        continue;
                    }
                    if (StringUtils.isNotEmpty(push.getDistance()) && (Double.parseDouble(push.getDistance()) / 1000 >= Double.parseDouble(taskPush.getDistance()))) {
                        // eidt by wlf 20200518 推送时要显示客户名
                        if (StringUtils.isNotEmpty(push.getRegistrationId())) {
                            String customerName = StringUtils.isEmpty(push.getCustomerName()) ? "" : push.getCustomerName();
                            String content = PushConfig.SIGN_OFF_AUTO_CONTENT.replaceAll("N", push.getSignOffAutoHour().toString()).replaceAll("C", customerName);
                            // 推送额外参数
                            JsonObject extra = new JsonObject();
                            extra.addProperty("type", PushConfig.SIGN_OFF_AUTO_STATE);
                            extra.addProperty("serviceNoticeId", push.getServiceNoticeId());
                            extra.addProperty("serviceNo", push.getServiceNo());
                            extra.addProperty("planId", push.getId());
                            extra.addProperty("enginnerId", push.getFseId());
                            extra.addProperty("enginnerName", push.getFseName());
                            JpushLog jpushLog = new JpushLog();
                            PushResult pushResult = null;
                            try {
                                JPushClientUtil.getInstance().initJPushClient(jPushConfig.getSecret(), jPushConfig.getAppkey());
                                pushResult = JPushClientUtil.getInstance().sendPush(push.getRegistrationId(), PushConfig.SIGN_OFF_AUTO_TITLE, content, extra);
                                jpushLog.setStatuscode(pushResult.statusCode + "");
                                jpushLog.setMsgId(pushResult.msg_id + "");
                                jpushLog.setSendno(pushResult.sendno + "");
                            } catch (APIConnectionException e) {
                                // Connection error, should retry later
                                log.error("Connection error, should retry later", e);
                            } catch (APIRequestException e) {
                                // Should review the error, and fix the request
                                log.error("Should review the error, and fix the request", e);
                                log.info("HTTP Status: " + e.getStatus());
                                log.info("Error Code: " + e.getErrorCode());
                                log.info("Error Message: " + e.getErrorMessage());
                                jpushLog.setStatuscode(e.getErrorCode() + "");
                                jpushLog.setMessage(e.getStatus() + "," + e.getErrorMessage());
                            }
                            // 保存推送日志
                            jpushLog.setEnginnerId(push.getFseId());
                            jpushLog.setType(PushConfig.ONE_PUSH);
                            jpushLog.setNoticeId(push.getServiceNoticeId());
                            jpushLog.setServiceNo(push.getServiceNo());
                            jpushLog.setRegistrationId(push.getRegistrationId());
                            jpushLog.setState(PushConfig.SIGN_OFF_AUTO_STATE);
                            jpushLog.setTitle(PushConfig.SIGN_OFF_AUTO_TITLE);
                            jpushLog.setContent(content);
                            jpushLog.setExtra(extra.toString());
                            jpushLog.setPushTime(date);
                            jpushLog.setCreateTime(date);
                            jpushLogMapper.insertJpushLog(jpushLog);

                            // 如果状态为0 说明推送成功
                            if ("0".equals(jpushLog.getStatuscode())) {

                                PlanDetails planDetails = new PlanDetails();
                                planDetails.setId(push.getId());
                                planDetails.setSignOffAutoPush("1");
                                planDetails.setSignOffAutoPushTime(departMent);
                                planDetailsMapper.updateStPlanDetails(planDetails);
                            }
                        } else {
                            PlanDetails planDetails = new PlanDetails();
                            planDetails.setId(push.getId());
                            planDetails.setSignOffAutoPush("1");
                            planDetails.setSignOffAutoPushTime(departMent);
                            planDetailsMapper.updateStPlanDetails(planDetails);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("程序异常", e.getMessage());
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signOffAuto(TaskPush taskPush) {
        try {
            Date date = new Date();
            List<TaskPush> taskPushes = planDetailsMapper.getSignOffAuto(taskPush);
            if (taskPushes != null && taskPushes.size() > 0) {
                for (TaskPush push : taskPushes) {
                    if (ObjectUtils.isEmpty(push.getPostX())) {
                        continue;
                    }
                    if (ObjectUtils.isEmpty(push.getPostY())) {
                        continue;
                    }
                    if (ObjectUtils.isEmpty(push.getLongitude())) {
                        continue;
                    }
                    if (ObjectUtils.isEmpty(push.getLatitude())) {
                        continue;
                    }

                    // 人员的实时经纬度
                    LngLat start = new LngLat(push.getPostX(), push.getPostY());

                    // 获取仪器的经纬度
                    LngLat end = new LngLat(push.getLongitude(), push.getLatitude());

                    // 计算获取两组经纬度的距离 取公里KM
                    double actualDistance = AMapUtils.calculateLineDistance(start, end) / 1000;
                    // 如果在这个范围内 不推送消息
                    if (actualDistance < Double.parseDouble(taskPush.getDistance())) {
                        continue;
                    }

                    // 更改数据为自动签离
                    ServiceDetails serviceDetails = new ServiceDetails();
                    serviceDetails.setFseId(push.getFseId());
                    serviceDetails.setServiceNoticeId(push.getServiceNoticeId());
                    serviceDetails.setState(5L);
                    //查询最新的信息
                    PlanDetails planDetailsNew = new PlanDetails();
                    planDetailsNew.setFseId(push.getFseId());
                    planDetailsNew.setServiceNoticeId(push.getServiceNoticeId());
                    List<PlanDetails> planDetailsList = planDetailsMapper.selectStPlanDetailsList(planDetailsNew);
                    if (planDetailsList.size() > 0) {
                        serviceDetails.setUpdateBy(planDetailsList.get(0).getId() + "");
                    }
                    serviceDetailsMapper.updateMyServiceDetails(serviceDetails);
                    // 更改数据为自动签离
                    PlanDetails planDetails = new PlanDetails();
                    planDetails.setId(push.getId());
                    planDetails.setState("5");
                    FseLocation fseLocation = new FseLocation();
                    fseLocation.setFseId(push.getFseId());
                    List<FseLocation> fseLocations = fseLocationMapper.selectFseLocationList(fseLocation);
                    if (fseLocations != null && fseLocations.size() > 0) {
                        planDetails.setSignOffLon(fseLocations.get(0).getPostx());
                        planDetails.setSignOffLat(fseLocations.get(0).getPosty());

                        /** 所有位置信息存入log表中，用于轨迹查询 */
                        FseLocationLog fseLocationLog = new FseLocationLog();
                        fseLocationLog.setAddress(fseLocations.get(0).getAddress());
                        fseLocationLog.setFseId(fseLocations.get(0).getFseId());
                        fseLocationLog.setFseName(fseLocations.get(0).getFseName());
                        fseLocationLog.setPostx(fseLocations.get(0).getPostx());
                        fseLocationLog.setPosty(fseLocations.get(0).getPosty());
                        fseLocationLog.setNetworkState(fseLocations.get(0).getNetworkState());
                        fseLocationLog.setReceiveDate(fseLocations.get(0).getReceiveDate());
                        fseLocationLog.setState(fseLocations.get(0).getState());
                        fseLocationLog.setStateDescribe(fseLocations.get(0).getStateDescribe());
                        fseLocationLog.setCreateTime(date);
                        fseLocationLog.setAltitude(fseLocations.get(0).getAltitude());
                        fseLocationLog.setSpeed(fseLocations.get(0).getSpeed());
                        fseLocationLog.setCourse(fseLocations.get(0).getCourse());
                        fseLocationLog.setType("4");
                        fseLocationLogMapper.insertFseLocationLog(fseLocationLog);

                    }
                    planDetails.setSignOff("1");
                    planDetails.setSignOffTime(date);
                    planDetailsMapper.updateStPlanDetails(planDetails);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("程序异常", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

    }


}
